package com.ankebio.mybatisgenerator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MybatisgeneratorApplication {

	public static void main(String[] args) throws Exception {
		List<String> warnings = new ArrayList<String>();
		boolean overwrite = true;
		File configFile = new File(MybatisgeneratorApplication.class.getClassLoader().getResource("generatorConfig.xml").getFile());
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
		Context context = config.getContext("default");
		String domainPackage = context.getJavaModelGeneratorConfiguration().getTargetPackage();
//		String rootPath=System.getProperty("user.dir")+"/src/main/";
		File domainPath=new File("src/main/java",packageToPath(domainPackage));
		File[] files = domainPath.listFiles();
		for (File file : files) {
			if(file.getName().endsWith("Example.java")){
				file.delete();
			}
		}
//		File mapperPath=new File(rootPath,"/resources/mapper");
		File mapperPath=new File("src/main/resources/mapper");
		File[] mappers = mapperPath.listFiles();
		regexHandler(mappers);
	}

	private static void regexHandler(File[] mappers) throws IOException {
		List<Pattern> patterns=new ArrayList<>();
		patterns.add(Pattern.compile("<sql id=\"Example_Where_Clause\">.+?</sql>",Pattern.MULTILINE|Pattern.DOTALL));
		patterns.add(Pattern.compile("<select id=\"selectByExample\".+?</select>",Pattern.MULTILINE|Pattern.DOTALL));
		patterns.add(Pattern.compile("<insert id=\"insert\".+?</insert>",Pattern.MULTILINE|Pattern.DOTALL));
		patterns.add(Pattern.compile("<update id=\"updateByPrimaryKey\".+?</update>",Pattern.MULTILINE|Pattern.DOTALL));
		for (File mapper : mappers) {
			System.out.println("正在处理……"+mapper.getName());
			StringBuilder sb = new StringBuilder();
			try(BufferedReader br = new BufferedReader(new FileReader(mapper))){
				String s = "";
				while ((s =br.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
					sb.append(s + "\r\n");//将读取的字符串添加换行符后累加存放在缓存中
				}
			}
			String content = sb.toString();
			for (Pattern pattern : patterns) {
				content = replaceContent(content, pattern);
			}
			content=content.replace("selectByPrimaryKey","getById");
			content=content.replace("deleteByPrimaryKey","delete");
			content=content.replace("insertSelective","add");
			content=content.replace("updateByPrimaryKeySelective","update");
			try(FileWriter fw=new FileWriter(mapper)){
				fw.write(content);
			}
		}
	}

	private static String replaceContent(String content, Pattern p) {
		Matcher m=p.matcher(content);
		while(m.find()){
//				System.out.println(m.group()+"   位置：["+m.start()+","+m.end()+"]");
			content=content.replace(m.group(),"");
		}
		return content;
	}

	private static void dom4jHandler(File[] mappers) throws DocumentException, IOException {
		SAXReader reader = new SAXReader();
		for (File mapper : mappers) {
			System.out.println("正在处理……"+mapper.getName());
			//1.创建Reader对象
			//2.加载xml
			Document document = reader.read(mapper);
			//3.获取根节点
			Element rootElement = document.getRootElement();
			Iterator iterator = rootElement.elementIterator();
			while (iterator.hasNext()){
				Element element = (Element) iterator.next();
				List<Attribute> attributes = element.attributes();
				for (Attribute attribute : attributes) {
					if(attribute.getValue().equals("Example_Where_Clause")
						|| attribute.getValue().equals("selectByExample")
						|| attribute.getValue().equals("insert")
						|| attribute.getValue().equals("updateByPrimaryKey")){
						rootElement.remove(element);
						break;
					}
				}
			}
			try(FileOutputStream fos = new FileOutputStream(mapper)){
				//设置输出格式
	             OutputFormat format = OutputFormat.createPrettyPrint();
	             //设置文件编码
	             format.setEncoding("UTF-8");
	             //将写好的文档document输出到指定XML文件中并关闭XMLWriter对象
	             XMLWriter xml = new XMLWriter(fos,format);
	             //有时候我们的内容text中会有诸如/、>之类的，我们要告诉XML,不要转义这些字符
	             xml.setEscapeText(false);
	             xml.write(document);
	             xml.close();
			}
		}
	}

	private static String packageToPath(String packageName) {
		String[] split = packageName.split("\\.");
		String path="";
		for (String s : split) {
			path+=s+"/";
		}
		path=path.substring(0,path.length()-1);
		return path;
	}
}
